package com.lzw.DailyAudit.service.dateAggregation_02.DailyAudit.service.dateAggregation_02;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.hooya.fa.eu.biz.DailyAudit.entity.DailyAuditStatus;
import com.hooya.fa.eu.biz.DailyAudit.entity.StkOrigDataCollect;
import com.hooya.fa.eu.biz.DailyAudit.entity.dto.CGDataDTO;
import com.hooya.fa.eu.biz.DailyAudit.mapper.DailyAuditStatusMapper;
import com.hooya.fa.eu.biz.DailyAudit.mapper.DailyMetaStkCustomsMapper;
import com.hooya.fa.eu.biz.DailyAudit.mapper.DailyTempJcjlMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@DS("fa_eu_daily")
public class Insert_CG {

    @Autowired
    private DailyTempJcjlMapper tempJcjlMapper;

    @Autowired
    private DailyMetaStkCustomsMapper metaStkCustomsMapper;

    @Autowired
    private CommonService commonService;

	@Autowired
	private DailyAuditStatusMapper statusMapper;

	@Transactional
	public void insert_cg(String currentDate) {
		try {

			String name = "insertCg-02";
			DailyAuditStatus dailyAuditStatus = statusMapper.selectStatus(name, currentDate);
			if(dailyAuditStatus != null && dailyAuditStatus.getFlag() == 1){
				log.info("{} - 该方法已执行，进行跳过！",name);
				return;
			}

			log.info("开始执行采购数据插入任务，开始日期：{}", currentDate);

            // 获取主要数据
            List<CGDataDTO> mainData = tempJcjlMapper.getCgData(currentDate);

            //重新设置belongs值 和 hthm的值
            mainData.forEach(f -> {
                if (f.getBelongs() != null && f.getBelongs().toLowerCase().startsWith("fds")) {
                    String[] parts = f.getBelongs().split("-");
                    f.setBelongs(parts[0]);
                }
                if (f.getHthm() != null && f.getHthm().contains("-")) {
                    String[] parts = f.getHthm().split("-");
                    if (parts.length > 0) {
                        String lastPart = parts[parts.length - 1];
                        if (lastPart.matches("\\d+")) {  // 检查是否为纯数字
                            StringBuilder result = new StringBuilder();
                            for (int i = 0; i < parts.length - 1; i++) {
                                if (i > 0) result.append("-");
                                result.append(parts[i]);
                            }
                            f.setHthm(result.toString());
                        }
                    }
                }
            });

            // 获取价格数据（只包含有价格的记录）
            List<CGDataDTO> priceData = metaStkCustomsMapper.getCgPriceData();

            // 合并主数据和价格数据
            Map<String, List<CGDataDTO>> PriceDataMap = priceData.stream().collect(Collectors.groupingBy(f -> f.getSku() + "|" + f.getInvoiceno()));
            List<CGDataDTO> mergeData = new ArrayList<>();
            for (CGDataDTO mainItem : mainData) {
                String key = mainItem.getCpbh() + "|" + mainItem.getHthm();
                if (PriceDataMap.containsKey(key)) {
                    List<CGDataDTO> cgDataDTOS = PriceDataMap.get(key);
                    cgDataDTOS.forEach(f -> {
                        CGDataDTO newItem = new CGDataDTO();
                        BeanUtils.copyProperties(mainItem, newItem);
                        newItem.setInvoicedate(f.getInvoicedate());
                        newItem.setPrice(f.getPrice());
                        newItem.setCurrency(f.getCurrency());
                        newItem.setQty(f.getQty());
                        newItem.setSku(f.getSku());
                        newItem.setInvoiceno(f.getInvoiceno());
                        mergeData.add(newItem);
                    });
                } else {
                    mergeData.add(mainItem);
                }
            }

            // 按qty排序并分组，获取第一条记录
            Map<String, List<CGDataDTO>> groupedData = mergeData.stream().sorted(Comparator.comparing(CGDataDTO::getQty, Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.groupingBy(f -> f.getCpbh() + f.getHthm() + f.getSl()));

            // 取每组第一条记录
            Map<String, CGDataDTO> withPriceDataMap = new HashMap<>();
            for (String key : groupedData.keySet()) {
                List<CGDataDTO> group = groupedData.get(key);
                if (!withPriceDataMap.containsKey(key) && !group.isEmpty()) {
                    withPriceDataMap.put(key, group.get(0));
                }
            }

            //  获得price为空的数据
            List<CGDataDTO> lastData = new ArrayList<>(withPriceDataMap.values());

            List<CGDataDTO> noPriceData = lastData.stream().filter(f -> f.getPrice() == null).collect(Collectors.toList());
            List<String> missingPriceSkuList = new ArrayList<>();
            if(!noPriceData.isEmpty()){
                List<String> skuList = noPriceData.stream()
                        .map(CGDataDTO::getCpbh)  // 获取 cpbh
                        .collect(Collectors.toList());
                List<CGDataDTO> giftAllPrice = metaStkCustomsMapper.getDataBySkuList(skuList);

                //修改lastData数据 查找异常的Sku记录到missingPriceSkuList
                noPriceData.forEach(row -> {
                    String cpbh = row.getCpbh();
                    String belongs = row.getBelongs();
                    String sheetNumber = row.getSheetnumber();

                    List<CGDataDTO> matchedData = giftAllPrice.stream()
                            .filter(item -> item.getSku().equals(cpbh) && item.getBelongs().equals(belongs))
                            .collect(Collectors.toList());

                    if (!matchedData.isEmpty()) {
                        // 按 invoiceDate 降序排序并取第一条
                        CGDataDTO Price = matchedData.stream().min((a, b) -> b.getInvoicedate().compareTo(a.getInvoicedate())).get();
                        lastData.stream().filter(f -> f.getSheetnumber().equals(sheetNumber)).forEach(f -> {
                            f.setPrice(Price.getPrice());
                            f.setInvoicedate(Price.getInvoicedate());
                            f.setCurrency(Price.getCurrency());
                        });
                    } else {
                        // 尝试查找替代的 belongs 值
                        String realBelongs;
                        String[] parts = belongs.split("-");
                        if (parts.length > 1) {
                            String a = parts[1];
                            String b = parts[0];

                            if ("costway".equals(b)) {
                                realBelongs = "fds";
                            } else if ("fds".equals(b)) {
                                realBelongs = "costway" + a;
                            } else {
                                realBelongs = "";
                            }
                        } else {
                            realBelongs = "";
                        }

                        // 在 giftAllPrice 中查找替代数据
                        List<CGDataDTO> changeData = giftAllPrice.stream()
                                .filter(item -> item.getSku().equals(cpbh) && item.getBelongs().equals(realBelongs))
                                .collect(Collectors.toList());

                        if (!changeData.isEmpty()) {
                            // 按 invoiceDate 降序排序并取第一条
                            CGDataDTO Price = changeData.stream().min((a, b) -> b.getInvoicedate().compareTo(a.getInvoicedate())).get();
                            // 更新 lastData 中对应记录的价格信息
                            lastData.stream()
                                    .filter(item -> item.getSheetnumber().equals(sheetNumber))
                                    .forEach(item -> {
                                        item.setPrice(Price.getPrice());
                                        item.setInvoicedate(Price.getInvoicedate());
                                        item.setCurrency(Price.getCurrency());
                                    });
                        } else {
                            // 设置默认值
                            lastData.stream()
                                    .filter(item -> item.getSheetnumber().equals(sheetNumber))
                                    .forEach(item -> {
                                        item.setPrice(0.0);
                                        item.setInvoicedate(null);
                                        item.setCurrency("");
                                    });
                            missingPriceSkuList.add(cpbh);
                        }
                    }
                });
            }

            // 输出结果信息
            if (!missingPriceSkuList.isEmpty()) {
                log.error("无价格：{}" , missingPriceSkuList);
            }

            // 数据验证
            commonService.dataVerificationCg(lastData);

            // 转换为StkOrigdataCollect对象并插入
            List<StkOrigDataCollect> records = commonService.convertGgToStkOrigDataCollect(lastData);

            commonService.batchInsert(records);

			// 修改执行状态
			commonService.UpdateOrInsertStatus(dailyAuditStatus, name, currentDate);

			log.info("insertCG执行成功");
        } catch (Exception e) {
            log.error("采购数据插入任务失败", e);
            throw new RuntimeException("采购数据插入任务失败", e);
        }
    }


}